<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RAGflow连接测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            padding: 30px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        }
        h1 {
            color: #333;
            margin-bottom: 10px;
        }
        .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }
        .test-section {
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        .test-section h2 {
            color: #667eea;
            font-size: 18px;
            margin-bottom: 15px;
        }
        .url-display {
            background: #fff;
            padding: 15px;
            border-radius: 6px;
            border: 1px solid #e0e0e0;
            word-break: break-all;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            color: #333;
            margin-bottom: 15px;
        }
        .button-group {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        button {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        .btn-secondary:hover {
            background: #5a6268;
        }
        .result-box {
            margin-top: 15px;
            padding: 15px;
            border-radius: 6px;
            font-size: 13px;
        }
        .result-box.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .result-box.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .result-box.info {
            background: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }
        .iframe-container {
            width: 100%;
            height: 500px;
            border: 2px solid #667eea;
            border-radius: 8px;
            overflow: hidden;
            margin-top: 15px;
        }
        .iframe-container iframe {
            width: 100%;
            height: 100%;
            border: none;
        }
        input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            margin-bottom: 10px;
        }
        input:focus {
            outline: none;
            border-color: #667eea;
        }
        .config-grid {
            display: grid;
            grid-template-columns: 120px 1fr;
            gap: 10px;
            align-items: center;
            margin-bottom: 15px;
        }
        .config-label {
            font-weight: 600;
            color: #555;
        }
        pre {
            background: #2d2d2d;
            color: #f8f8f2;
            padding: 15px;
            border-radius: 6px;
            overflow-x: auto;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🤖 RAGflow连接诊断工具</h1>
        <p class="subtitle">用于测试和诊断RAGflow AI客服连接问题</p>

        <!-- 配置部分 -->
        <div class="test-section">
            <h2>📝 配置信息</h2>
            <div class="config-grid">
                <label class="config-label">服务地址:</label>
                <input type="text" id="baseUrl" value="http://localhost" placeholder="例如: http://localhost:8089">
            </div>
            <div class="config-grid">
                <label class="config-label">Shared ID:</label>
                <input type="text" id="sharedId" value="ec1da38caef211f088ef72ae004f33d4">
            </div>
            <div class="config-grid">
                <label class="config-label">Auth Token:</label>
                <input type="text" id="authToken" value="Y3NjMyMmJhYjNmOTExZjBiMGY2MzJhNz">
            </div>
            <div class="url-display" id="fullUrl"></div>
            <div class="button-group">
                <button class="btn-primary" onclick="updateUrl()">🔄 更新URL</button>
                <button class="btn-secondary" onclick="copyUrl()">📋 复制URL</button>
            </div>
        </div>

        <!-- 连接测试 -->
        <div class="test-section">
            <h2>🔍 连接测试</h2>
            <div class="button-group">
                <button class="btn-primary" onclick="testPing()">测试服务可达性</button>
                <button class="btn-primary" onclick="testCORS()">测试跨域请求</button>
                <button class="btn-primary" onclick="openInNewTab()">在新标签页打开</button>
                <button class="btn-secondary" onclick="clearResults()">清除结果</button>
            </div>
            <div id="testResults"></div>
        </div>

        <!-- iframe预览 -->
        <div class="test-section">
            <h2>👁️ iframe预览</h2>
            <button class="btn-primary" onclick="loadIframe()">加载聊天窗口</button>
            <button class="btn-secondary" onclick="clearIframe()">清除iframe</button>
            <div id="iframeContainer"></div>
        </div>

        <!-- 诊断信息 -->
        <div class="test-section">
            <h2>🔧 环境诊断</h2>
            <button class="btn-primary" onclick="showDiagnostics()">显示诊断信息</button>
            <div id="diagnostics"></div>
        </div>
    </div>

    <script>
        // 更新URL显示
        function updateUrl() {
            const baseUrl = document.getElementById('baseUrl').value;
            const sharedId = document.getElementById('sharedId').value;
            const authToken = document.getElementById('authToken').value;
            const fullUrl = `${baseUrl}/next-chats/share?shared_id=${sharedId}&from=chat&auth=${authToken}&locale=zh`;
            document.getElementById('fullUrl').textContent = fullUrl;
            return fullUrl;
        }

        // 复制URL
        function copyUrl() {
            const url = updateUrl();
            navigator.clipboard.writeText(url).then(() => {
                addResult('success', '✅ URL已复制到剪贴板');
            }).catch(err => {
                addResult('error', '❌ 复制失败: ' + err.message);
            });
        }

        // 测试服务可达性
        async function testPing() {
            const baseUrl = document.getElementById('baseUrl').value;
            addResult('info', '🔄 正在测试服务可达性...');
            
            try {
                const response = await fetch(baseUrl, { 
                    mode: 'no-cors',
                    method: 'HEAD'
                });
                addResult('success', `✅ 服务可达！基础URL: ${baseUrl}`);
            } catch (error) {
                addResult('error', `❌ 服务不可达: ${error.message}\n请检查RAGflow服务是否启动，端口是否正确`);
            }
        }

        // 测试CORS
        async function testCORS() {
            const url = updateUrl();
            addResult('info', '🔄 正在测试跨域请求...');
            
            try {
                const response = await fetch(url, {
                    method: 'GET',
                    mode: 'cors'
                });
                
                if (response.ok) {
                    addResult('success', `✅ 请求成功！状态码: ${response.status}`);
                } else {
                    addResult('error', `⚠️ 请求失败！状态码: ${response.status} ${response.statusText}`);
                }
            } catch (error) {
                if (error.message.includes('CORS')) {
                    addResult('error', `❌ CORS错误: ${error.message}\n\n可能的解决方案:\n1. 配置RAGflow允许跨域\n2. 使用Nginx反向代理\n3. 在同一域名下访问`);
                } else if (error.message.includes('Failed to fetch')) {
                    addResult('error', `❌ 连接失败: 无法连接到服务器\n\n请检查:\n1. RAGflow服务是否启动\n2. 端口号是否正确\n3. 防火墙设置`);
                } else {
                    addResult('error', `❌ 错误: ${error.message}`);
                }
            }
        }

        // 在新标签页打开
        function openInNewTab() {
            const url = updateUrl();
            window.open(url, '_blank');
            addResult('info', '📤 已在新标签页打开URL');
        }

        // 加载iframe
        function loadIframe() {
            const url = updateUrl();
            const container = document.getElementById('iframeContainer');
            
            container.innerHTML = `
                <div class="iframe-container">
                    <iframe src="${url}" onload="iframeLoaded()" onerror="iframeError()"></iframe>
                </div>
            `;
            
            addResult('info', '🔄 正在加载iframe...');
            
            // 设置超时检测
            setTimeout(() => {
                const results = document.getElementById('testResults');
                if (!results.textContent.includes('iframe加载成功')) {
                    addResult('error', '⏱️ iframe加载超时（10秒）\n可能原因：服务器响应慢或连接失败');
                }
            }, 10000);
        }

        // iframe加载成功
        function iframeLoaded() {
            addResult('success', '✅ iframe加载成功！');
        }

        // iframe加载失败
        function iframeError() {
            addResult('error', '❌ iframe加载失败！');
        }

        // 清除iframe
        function clearIframe() {
            document.getElementById('iframeContainer').innerHTML = '';
            addResult('info', '🗑️ 已清除iframe');
        }

        // 显示诊断信息
        function showDiagnostics() {
            const diagnostics = {
                '浏览器': navigator.userAgent,
                '当前URL': window.location.href,
                '协议': window.location.protocol,
                '主机': window.location.host,
                '时间': new Date().toLocaleString('zh-CN'),
                'Cookie启用': navigator.cookieEnabled,
                '在线状态': navigator.onLine
            };

            let html = '<pre>';
            html += '=== 环境诊断信息 ===\n\n';
            for (const [key, value] of Object.entries(diagnostics)) {
                html += `${key}: ${value}\n`;
            }
            html += '\n=== RAGflow配置 ===\n\n';
            html += `服务地址: ${document.getElementById('baseUrl').value}\n`;
            html += `Shared ID: ${document.getElementById('sharedId').value}\n`;
            html += `Auth Token: ${document.getElementById('authToken').value}\n`;
            html += `完整URL: ${updateUrl()}\n`;
            html += '</pre>';

            document.getElementById('diagnostics').innerHTML = html;
        }

        // 添加测试结果
        function addResult(type, message) {
            const results = document.getElementById('testResults');
            const div = document.createElement('div');
            div.className = `result-box ${type}`;
            div.textContent = message;
            div.style.whiteSpace = 'pre-wrap';
            results.appendChild(div);
            results.scrollTop = results.scrollHeight;
        }

        // 清除结果
        function clearResults() {
            document.getElementById('testResults').innerHTML = '';
        }

        // 页面加载时初始化
        window.onload = function() {
            updateUrl();
            
            // 自动运行快速诊断
            addResult('info', '👋 欢迎使用RAGflow连接诊断工具\n\n建议步骤:\n1. 确认配置信息是否正确\n2. 点击"测试服务可达性"\n3. 点击"测试跨域请求"\n4. 如果都成功，点击"加载聊天窗口"');
        };

        // 监听输入变化
        ['baseUrl', 'sharedId', 'authToken'].forEach(id => {
            document.getElementById(id).addEventListener('input', updateUrl);
        });
    </script>
</body>
</html>

